package yoshop_ast

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"gitee.com/libs_2/yoshop_ast/model"
)

// CreateGoods 创建商品
func (c *Client) CreateGoods(ctx context.Context, req *model.SaveGoodsInfoReq) error {
	reqBody, _ := json.Marshal(req)

	body, err := c.doPost(ctx, "/index.php?s=/store/goods/add", bytes.NewReader(reqBody))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}

func (c *Client) GetGoodsList(ctx context.Context, pageIndex int, catId int, listType model.GoodsListType) (model.GoodsListData, error) {
	body, err := c.doGet(ctx, fmt.Sprintf("/index.php?s=/store/goods/list&page=%d&listType=%s&categoryId=%d", pageIndex, listType, catId))
	if err != nil {
		return model.GoodsListData{}, err
	}

	// fmt.Printf("%s\n", string(body))

	var res model.GetGoodsListResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return model.GoodsListData{}, err
	}
	if res.Status != 200 {
		return model.GoodsListData{}, errors.New(res.Msg)
	}

	return res.Data.List, nil
}

func (c *Client) GetGoodsInfo(ctx context.Context, goodsId int64) (*model.GoodsItem, error) {
	body, err := c.doGet(ctx, fmt.Sprintf("/index.php?s=/store/goods/detail&goodsId=%d", goodsId))
	if err != nil {
		return nil, err
	}

	// fmt.Printf("%s\n", string(body))

	var res model.GetGoodsInfoResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return nil, err
	}
	if res.Status != 200 {
		return nil, errors.New(res.Msg)
	}

	return &res.Data.GoodsInfo, nil
}

// EditGoods 编辑商品
func (c *Client) EditGoods(ctx context.Context, req *model.SaveGoodsInfoReq) error {
	reqBody, _ := json.Marshal(req)

	body, err := c.doPost(ctx, "/index.php?s=/store/goods/edit", bytes.NewReader(reqBody))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}

// DeleteGoods 删除商品
func (c *Client) DeleteGoods(ctx context.Context, goodsID ...int64) error {
	reqBody, _ := json.Marshal(map[string][]int64{
		"goodsIds": goodsID,
	})

	body, err := c.doPost(ctx, "/index.php?s=/store/goods/delete", bytes.NewReader(reqBody))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}
